/*******************************************************************************
 * Copyright (C) 2017 ShenZhen Powerdata Information Technology Co.,Ltd All
 * Rights Reserved. 本软件为深圳博安达开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、 复制、修改或发布本软件.
 ******************************************************************************/
app.directive('szboandaFreeSelect',function() {
	return {
		restrict : 'A',
		replace : false,
		scope : {
			ngConfig : '=',
			ngModelValue : '=',
			ngModelObject : '=',
			ngModel : '=',
			dataOptions : '@fsDataOptions',// 绑定策略
			ngDisabled : '=',
			divid : '@',
			inputId : '@'
		},
		template : '<div ng-class="hasClass()">\
		<div ng-if="!ngConfig.checkStyle || ngConfig.checkStyle==\'radio\'">\
			<ui-select ng-model="$parent.$parent.ngModelObject" on-select="changeSelected($item, $model)" ng-disabled="ngDisabled">\
            	<ui-select-match repeat="item in (dataList) track by item.value">\
			        <span ng-bind="$select.selected.label"></span>\
			    </ui-select-match>\
			    <ui-select-choices repeat="item in (dataList | filter: $select.search) track by item.value">\
			        <span ng-bind="item.label"></span>\
			    </ui-select-choices>\
			</ui-select>\
		</div>\
		<div ng-if="ngConfig.checkStyle && ngConfig.checkStyle==\'checkbox\'" class="multiple-select">\
			<ui-select multiple ng-model="$parent.$parent.ngModelObject" close-on-select="false" id="" ng-disabled="ngDisabled" on-remove="changeSelected($item, $model)" on-select="changeSelected($item, $model)" style="">\
			     <ui-select-match>\
			         <span ng-bind="$item.label"></span>\
			     </ui-select-match>\
			     <ui-select-choices repeat="item in dataList | filter: {label: $select.search}">\
			         <span ng-bind="item.label"></span>\
			     </ui-select-choices>\
			 </ui-select>\
		</div>\
		<div ng-if="ngConfig.checkStyle && ngConfig.checkStyle==\'tree\'" ng-class="treeClass()">\
			<input type="text" ng-model="ngModelObject.name" style="width: 234px;" class="form-control" ng-click="switchOptions();" readonly>\
			<div save-content="selected-html" class="dropdown-menu tree-select-choices" ng-show="switchFlag" ng-mouseleave="close()">\
	            <treecontrol class="tree-classic"  tree-model="treedata" selected-node="$parent.ngModelObject" expanded-nodes="expandedNodes" options="treeOptions" on-selection="changeSelected(node, selected	)">\
	                {{node.name}}\
	            </treecontrol>\
				<div class="tree-select-btns">\
					<span class="btn" ng-click="clear()">清空</span>\
					<span class="btn" ng-click="close()">关闭</span>\
			 	</div>\
	        </div>\
        </div>\
		<div ng-if="ngConfig.checkStyle && ngConfig.checkStyle==\'cascade\'" ng-class="treeClass()">\
			<ui-select ng-model="cascadeModelList[0]" on-select="changeSelected($item, $model)" ng-disabled="ngDisabled">\
	        	<ui-select-match repeat="item in (dataList) track by item.value">\
			        <span ng-bind="$select.selected.label"></span>\
			    </ui-select-match>\
			    <ui-select-choices repeat="item in (dataList | filter: $select.search) track by item.value">\
			        <span ng-bind="item.label"></span>\
			    </ui-select-choices>\
			</ui-select>\
			<ui-select ng-model="cascadeModelList[1]" on-select="changeSelected($item, $model)" ng-disabled="ngDisabled">\
	        	<ui-select-match repeat="item in (getDataList(cascadeModelList[0])) track by item.value">\
			        <span ng-bind="$select.selected.label"></span>\
			    </ui-select-match>\
			    <ui-select-choices repeat="item in (getDataList(cascadeModelList[0] | filter: $select.search) track by item.value">\
			        <span ng-bind="item.label"></span>\
			    </ui-select-choices>\
			</ui-select>\
		</div>\
		<input id="free-select-valid-code" ng-show="false" type="text" \
        	data-options="{{dataOptions}}"\
        	class="easyui-validatebox" ng-value="getValidateValue()"/>\
	</div>',
		link : function(scope, element, attrs) {
			scope.shallowCopy = function(src, dst) {
                if (angular.isArray(src)) {
                    dst = dst || [];

                    for ( var i = 0; i < src.length; i++) {
                        dst[i] = src[i];
                    }
                } else if (angular.isObject(src)) {
                    dst = dst || {};

                    for (var key in src) {
                        if (hasOwnProperty.call(src, key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
                            dst[key] = src[key];
                        }
                    }
                }

                return dst || src;
            }
			scope.treeOptions = {
					nodeChildren: "children",
				    dirSelectable: true,
				    injectClasses: {
				        ul: "a1",
				        li: "a2",
				        liSelected: "a7",
				        iExpanded: "a3",
				        iCollapsed: "a4",
				        iLeaf: "a5",
				        label: "a6",
				        labelSelected: "a8"
				    },
					isLeaf : function(node) {
						
                        return !node.isParent || node.isParent != 'true';
					},
					isSelectable :function(node) {
						return !node.isParent || node.isParent != 'true';
					},
					equality : function (a, b) {
                        if (a === undefined || b === undefined || a === null || b === null)
                            return false;
                        a = scope.shallowCopy(a);
                        a["children"] = [];
                        b = scope.shallowCopy(b);
                        b["children"] = [];
                        return angular.equals(a, b);
                    },
                   
			};
			scope.switchOptions = function(){
				scope.switchFlag = !scope.switchFlag;
				return scope.switchFlag;
			}
			scope.treeClass = function(){
				if(scope.switchFlag){
					return 'dropdown open';
				}else{
					return 'dropdown';
				}
			}
			scope.clear = function(){
				scope.ngModelObject = null;
				scope.switchFlag = true;
			}
			scope.close = function(){
				scope.switchFlag = false;
			}
			
			//支持表单校验
			scope.hasClass = function (className) {
				
                if($(element).find("#free-select-valid-code").hasClass("validatebox-invalid")){
                    if(!scope.model || !scope.model.length){
                        return 'pt-invalid';
                    }
                }
                return ''
            };
			//反显
            scope._invertList = function(dataList, hasChildren, childrenName){
            	
            	if(!dataList || !dataList.length){
            		return false;
            	}
            	
            	var len = dataList.length;
				for(var i=0;i<len;i++){
					var node = dataList[i];
					if(node.value == scope.ngModelValue){
						scope.ngModelObject = node;
						return true;
					}
					if(hasChildren && childrenName && node[childrenName] && node[childrenName].length){
						if(scope._invertList(node[childrenName], true, childrenName)){
							return true;
						}
					}
				}
				
				return false;
            }
			scope._invert = function(){
				
				if(!scope.ngConfig.checkStyle || scope.ngConfig.checkStyle=='radio'){
					if(scope.dataList && scope.ngModelValue && !scope.ngModelObject){
						scope._invertList(scope.dataList);
					}
						
				}else if(scope.ngConfig.checkStyle && scope.ngConfig.checkStyle=='tree'){
					
					if(scope.dataList && scope.ngModelValue && !scope.ngModelObject){
						scope._invertList(scope.dataList, true, 'children');
					}
						
				}else if(scope.ngConfig.checkStyle && scope.ngConfig.checkStyle=='checkbox'){ 
					if(scope.ngModelValue){
						var objectList = new Array();
						var len = scope.ngModelValue.length;
						for(var i=0;i<len;i++){
							var valueNow = scope.ngModelValue[i];
							var len = scope.dataList.length;
							for(var j=0;j<len;j++){
								var node = scope.dataList[j];
								if(node.value == valueNow){
									objectList.push(node);
								}
							}
						}
						scope.ngModelObject = objectList;
					}
					
					
				}else if(scope.ngConfig.dataType=='local'){
					 
				}
					
			}
        	
			//加载数据
			if(scope.ngConfig.dataType=='remote'){
				$.ajax({
	                url : scope.ngConfig.dataUrl,
	                type : "POST",
	                dataType : 'json',
	                async : false,
	                contentType : 'application/json',
	                data : JSON.stringify(scope.ngConfig.dataFilter ? scope.ngConfig.dataFilter : {}),
	                success : function (response){
	                	
	                	var nodeList = null;
	                	if(scope.ngConfig.ajaxModelFilter){
	                		nodeList = scope.ngConfig.ajaxModelFilter(response);
	                	}else{
	                		nodeList = response.model;
	                	}
	                	if(nodeList){
	                		if(!scope.ngConfig.checkStyle || scope.ngConfig.checkStyle=='radio'){
		                		nodeList.unshift({value:null,label:'请选择'});
	                		}
	                		
	                		scope.dataList = nodeList;
	                		scope._invert();
	                	}
	                	if(scope.ngConfig.checkStyle && scope.ngConfig.checkStyle=='tree'){
	                		scope.treedata = nodeList;
	                		if(scope.treedata[0]){
		                		scope.expandedNodes = [scope.treedata[0]];
	                		}
	                	}
					}
	             });
			}else if(scope.ngConfig.dataType=='local'){
				scope.dataList = scope.ngConfig.dataList;
        		scope._invert();
			}
			//数据传递ngModelObject -> ngModelValue
			if(!scope.ngConfig.checkStyle || scope.ngConfig.checkStyle=='radio'){
				scope.changeSelected = function(item, model){
					scope.ngModelObject = item;
					scope.ngModelValue = item.value;
					scope.ngModelLabel = item.label;
					if(scope.ngConfig.callback && scope.ngConfig.callback.onChange){
						scope.ngConfig.callback.onChange(item);
					}
				}
			}else if(scope.ngConfig.checkStyle && scope.ngConfig.checkStyle=='tree'){
				scope.changeSelected = function(node, selected, $parentNode, $index, $first, $middle, $last, $odd, $even){
					scope.ngModelObject = node;
					scope.ngModelValue = node.value;
					if(scope.ngConfig.callback && scope.ngConfig.callback.onChange){
						scope.ngConfig.callback.onChange(node);
					}
				}
			}else if(scope.ngConfig.checkStyle && scope.ngConfig.checkStyle=='checkbox'){
				if(!scope.ngModelObject){
					scope.ngModelObject = new Array();
				}
				scope.changeSelected = function(item, model){
					scope.ngModelObject;
					var valueList = new Array();
					if(scope.ngModelObject && scope.ngModelObject.length){
						var len = scope.ngModelObject.length;
						for(var i=0; i<len; i++){
							valueList.push(scope.ngModelObject[i].value);
						}
					}
					scope.ngModelValue = valueList;
					if(scope.ngConfig.callback && scope.ngConfig.callback.onChange){
						scope.ngConfig.callback.onChange(scope.ngModelObject);
					}
					
				}
			}
			
			//表单验证以及数据由object向value的传递
			
			if(!scope.ngConfig.checkStyle || scope.ngConfig.checkStyle=='radio'){
				scope.getValidateValue = function(){
					return scope.ngModelObject;
				};
			}else if(scope.ngConfig.checkStyle && scope.ngConfig.checkStyle=='tree'){
				
					scope.getValidateValue = function(){
						return scope.ngModelObject;
					};
			}else{
				scope.getValidateValue = function(){
					if(scope.ngModelObject && scope.ngModelObject.length){
						return 'szboanda-validate-value';
					}else{
						return null;
					}
				};
			}
			
			scope.watch1 = scope.$watch('ngModelValue',function(newValue, oldValue){
				
				if(newValue && !oldValue){
					scope._invert();
					scope.watch1();
				}
			})
		}

	};
});
